package com.medvalley.tcm.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.medvalley.tcm.base.BusinessException;
import com.medvalley.tcm.base.QuestionType;
import com.medvalley.tcm.dao.MindQuestionnaireDao;
import com.medvalley.tcm.domain.MindQuestionnaire;
import com.medvalley.tcm.vo.inputvo.MindQuestionnaireInputVo;
import com.medvalley.tcm.vo.outputvo.MindQuestionnaireOutputVo;
import lombok.extern.java.Log;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.List;

@Service
public class MindQuestionnaireService {

    private static Logger logger = LoggerFactory.getLogger(MindQuestionnaireService.class);

    @Autowired
    private MindQuestionnaireDao mindQuestionnaireDao;

    @Autowired
    private MusicService musicService;

    public long addUser(MindQuestionnaireInputVo inputVo) {
        MindQuestionnaire mindQuestionnaire = new MindQuestionnaire();
        mindQuestionnaire.setPhone(inputVo.getPhone());
        mindQuestionnaire.setName(inputVo.getName());
        mindQuestionnaire.setBirthday(inputVo.getBirthday());
        mindQuestionnaire.setGender(inputVo.getGender());
        mindQuestionnaire.setCreateTime(new Date());
        mindQuestionnaireDao.save(mindQuestionnaire);
        return mindQuestionnaire.getId();
    }

    public MindQuestionnaireOutputVo submitAnswer(MindQuestionnaireInputVo inputVo, long userId) {


        MindQuestionnaireOutputVo mindQuestionnaireOutputVo = new MindQuestionnaireOutputVo();
        MindQuestionnaire mindQuestionnaire = mindQuestionnaireDao.findById(inputVo.getId()).orElseThrow(() -> new BusinessException("用户信息不存在"));
        int type = inputVo.getType();
        mindQuestionnaire.setAnswer(inputVo.getAnswer());
        mindQuestionnaire.setType(type);
        this.score(inputVo.getAnswer(), type, mindQuestionnaire);
        mindQuestionnaireDao.save(mindQuestionnaire);
        try {
            musicService.recommendMusic(userId, type, QuestionType.getDesc(type));
        } catch (Exception e) {
            logger.error(" recommend music error,userId;{},phone:{},questionType:{} ", userId, type, inputVo.getType(), e);
        }
        mindQuestionnaireOutputVo.setName(mindQuestionnaire.getName());
        mindQuestionnaireOutputVo.setPhone(mindQuestionnaire.getPhone());
        mindQuestionnaireOutputVo.setScore(mindQuestionnaire.getScore());
        return mindQuestionnaireOutputVo;
    }

    public List<MindQuestionnaireOutputVo> listByPhone(String phone, int type) {
        List<MindQuestionnaireOutputVo> mindQuestionnaireOutputVos = Lists.newArrayList();
        List<MindQuestionnaire> mindQuestionnaireList = mindQuestionnaireDao.findAllByPhoneAndTypeOrderByIdDesc(phone, type);
        if (!CollectionUtils.isEmpty(mindQuestionnaireList)) {
            for (MindQuestionnaire m : mindQuestionnaireList) {
                MindQuestionnaireOutputVo outputVo = new MindQuestionnaireOutputVo();
                outputVo.setId(m.getId());
                outputVo.setScore(m.getScore());
                outputVo.setName(m.getName());
                outputVo.setGender(m.getGender());
                outputVo.setBirthday(m.getBirthday());
                outputVo.setAnswer(m.getAnswer());
                outputVo.setCreateDate(DateFormatUtils.format(m.getCreateTime(), "yyyy-MM-dd"));
                mindQuestionnaireOutputVos.add(outputVo);
            }
        }
        return mindQuestionnaireOutputVos;
    }

    public MindQuestionnaireOutputVo detailById(long id) {
        MindQuestionnaire m = mindQuestionnaireDao.findById(id)
                .orElseThrow(() -> new BusinessException("没有查到改记录"));
        MindQuestionnaireOutputVo mindQuestionnaireOutputVo = new MindQuestionnaireOutputVo();
        mindQuestionnaireOutputVo.setId(id);
        mindQuestionnaireOutputVo.setScore(m.getScore());
        mindQuestionnaireOutputVo.setName(m.getName());
        mindQuestionnaireOutputVo.setGender(m.getGender());
        mindQuestionnaireOutputVo.setBirthday(m.getBirthday());
        mindQuestionnaireOutputVo.setCreateDate(DateFormatUtils.format(m.getCreateTime(), "yyyy-MM-dd"));
        return mindQuestionnaireOutputVo;
    }

    /**
     * @param answer {"anxiety":"0,2,3","depression":"2,3","tired":"3,4"}
     * @return {"anxiety":23.5,"depression":45,"tired":56}
     */
    private void score(String answer, int type, MindQuestionnaire mindQuestionnaire) {
        JSONObject jsonObjectAnswer = JSONObject.parseObject(answer);
        if (type == QuestionType.ANXIETY.getCode()) {
            // 焦虑
            float anxietyFinalScore = 0f;
            String anxietyAnswer = jsonObjectAnswer.getString("anxiety");
            String[] anxietyScores = anxietyAnswer.split(",");
            for (String s : anxietyScores) {
                anxietyFinalScore = anxietyFinalScore + Integer.valueOf(s);
            }
            anxietyFinalScore = anxietyFinalScore * 1.25f;
            if (anxietyFinalScore <= 49) {
                mindQuestionnaire.setResult("无焦虑");
            } else if (anxietyFinalScore <= 59) {
                mindQuestionnaire.setResult("轻度焦虑");
            } else if (anxietyFinalScore <= 69) {
                mindQuestionnaire.setResult("中度焦虑");
            } else {
                mindQuestionnaire.setResult("重度焦虑");
            }
            mindQuestionnaire.setScore(String.valueOf(anxietyFinalScore));
            return;
        } else if (type == QuestionType.DEPRESSION.getCode()) {
            // 抑郁
            float depressionFinalScore = 0f;
            String depressionAnswer = jsonObjectAnswer.getString("depression");
            String[] depressionScores = depressionAnswer.split(",");
            for (String s : depressionScores) {
                depressionFinalScore = depressionFinalScore + Integer.valueOf(s);
            }
            depressionFinalScore = depressionFinalScore * 1.25f;
            if (depressionFinalScore <= 52) {
                mindQuestionnaire.setResult("无抑郁");
            } else if (depressionFinalScore <= 62) {
                mindQuestionnaire.setResult("轻度抑郁");
            } else if (depressionFinalScore <= 72) {
                mindQuestionnaire.setResult("中度抑郁");
            } else {
                mindQuestionnaire.setResult("重度抑郁");
            }
            mindQuestionnaire.setScore(String.valueOf(depressionFinalScore));
            return;
        } else if (type == QuestionType.TIRED.getCode()) {
            // 疲劳
            String tiredAnswer = jsonObjectAnswer.getString("tired");
            String[] tiredScores = tiredAnswer.split(",");
            float tiredFinalScore = 0f;
            for (String s : tiredScores) {
                tiredFinalScore = tiredFinalScore + Integer.valueOf(s);
            }
            tiredFinalScore = tiredFinalScore * 25 / 14;
            if (tiredFinalScore <= 49) {
                mindQuestionnaire.setResult("无疲劳");
            } else if (tiredFinalScore <= 59) {
                mindQuestionnaire.setResult("轻度疲劳");
            } else if (tiredFinalScore <= 69) {
                mindQuestionnaire.setResult("中度疲劳");
            } else {
                mindQuestionnaire.setResult("重度疲劳");
            }
            mindQuestionnaire.setScore(String.valueOf(tiredFinalScore));
            return;
        } else if (type == QuestionType.XINLI.getCode()) {
            // 心里压力
            String xlyl = jsonObjectAnswer.getString("pressure");
            String[] xlylScores = xlyl.split(",");
            float xlylFinalScore = 0f;
            for (String s : xlylScores) {
                xlylFinalScore = xlylFinalScore + Integer.valueOf(s);
            }
            if (xlylFinalScore <= 5) {
                mindQuestionnaire.setResult("无/低压力");
            } else if (xlylFinalScore <= 10) {
                mindQuestionnaire.setResult("正常压力范围");
            } else if (xlylFinalScore <= 15) {
                mindQuestionnaire.setResult("压力较大");
            } else {
                mindQuestionnaire.setResult("压力过大");
            }

            mindQuestionnaire.setScore(String.valueOf(xlylFinalScore));
            return;
        } else if (type == QuestionType.SHIMIAN.getCode()) {
            // 失眠
            String shiMian = jsonObjectAnswer.getString("insomnia");
            String[] shiMianScores = shiMian.split(",");
            float shiMianFinalScore = 0f;
            for (String s : shiMianScores) {
                shiMianFinalScore = shiMianFinalScore + Integer.valueOf(s);
            }
            if (shiMianFinalScore <= 4) {
                mindQuestionnaire.setResult("无睡眠障碍");
            } else if (shiMianFinalScore <= 6) {
                mindQuestionnaire.setResult("可疑失眠");
            } else {
                mindQuestionnaire.setResult("失眠");
            }
            mindQuestionnaire.setScore(String.valueOf(shiMianFinalScore));
            return;
        }
        mindQuestionnaire.setScore("0");
    }

}
